'use client';

import { useState, useEffect } from 'react';
import { Container, Box, Typography } from '@mui/material';
import Navbar from '@/components/Navbar';
import HeroSection from '@/components/home/HeroSection';
import ProjectList from '@/components/home/ProjectList';
import CreateProjectDialog from '@/components/home/CreateProjectDialog';
import DatasetCategories from '@/components/home/DatasetCategories';

export default function HomePage() {
  const [projects, setProjects] = useState([]);
  const [loading, setLoading] = useState(true);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);

  useEffect(() => {
    fetchProjects();
  }, []);

  const fetchProjects = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/projects');
      
      if (!response.ok) {
        throw new Error('Failed to fetch projects');
      }
      
      const data = await response.json();
      
      // 如果API返回的数据为空或少于8个项目，使用模拟数据
      if (!data || data.length === 0) {
        throw new Error('No projects returned from API');
      }
      
      setProjects(data);
    } catch (error) {
      console.error('Error fetching projects:', error);
      // 使用mock数据 - 8个相同的项目
      const mockProjects = Array.from({ length: 8 }, (_, index) => ({
        id: index + 1,
        name: '中医模型微调',
        description: '针对中医的智慧模型',
        updateAt: new Date(Date.now() - 8 * 60 * 60 * 1000).toISOString(), // 8小时前
        _count: {
          Questions: 0,
          Datasets: 0
        }
      }));
      console.log('使用模拟数据:', mockProjects.length, '个项目');
      setProjects(mockProjects);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateProject = () => {
    // 处理创建项目的逻辑
    setCreateDialogOpen(true);
  };

  const handleCloseCreateDialog = () => {
    setCreateDialogOpen(false);
  };

  return (
    <Box sx={{ minHeight: '100vh', bgcolor: '#f5f5f5' }}>
      <Navbar />
      <HeroSection onCreateProject={handleCreateProject} />
      
      <Container maxWidth="xl" sx={{ py: 4 }}>
        {/* 新增数据集分类模块 */}
        <DatasetCategories />
        
        <ProjectList projects={projects} onCreateProject={handleCreateProject} />
      </Container>
      
      <CreateProjectDialog 
        open={createDialogOpen} 
        onClose={handleCloseCreateDialog} 
      />
    </Box>
  );
}